package com.senlingspace.common.annotation;

import com.senlingspace.common.request.PaymentRequest;
import com.senlingspace.common.request.RepaymentRequest;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Base64;

/**
 * 自定义注解的校验器
 *
 * @author lebronjames
 * @date 2024/07/27
 */
public class AuthCodeValidator implements ConstraintValidator<ValidAuthCode, Object> {

    @Override
    public boolean isValid(Object request, ConstraintValidatorContext context) {

        if (request instanceof PaymentRequest) {
            PaymentRequest paymentRequest = (PaymentRequest) request;
            String paymentMethod = paymentRequest.getPaymentMethod();
            String authCode = paymentRequest.getAuthCode();

            return !extracted(context, paymentMethod, authCode);
        } else if (request instanceof RepaymentRequest) {
            RepaymentRequest repaymentRequest = (RepaymentRequest) request;
            String paymentMethod = repaymentRequest.getPaymentMethod();
            String authCode = repaymentRequest.getAuthCode();

            return !extracted(context, paymentMethod, authCode);
        }
        return true;
    }

    private boolean extracted(ConstraintValidatorContext context, String paymentMethod, String authCode) {
        if (paymentMethod == null || (!paymentMethod.equals(PaymentRequest.CASH_PAY) && !paymentMethod.equals(PaymentRequest.ONLINE_PAY))) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("用户购买方式无效！")
                    .addPropertyNode("paymentMethod")
                    .addConstraintViolation();
            return true;
        }

        if (PaymentRequest.ONLINE_PAY.equals(paymentMethod)) {
            if (authCode == null || authCode.isEmpty()) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("用户授权码不能为空！")
                        .addPropertyNode("authCode")
                        .addConstraintViolation();
                return true;
            }

            if (!isBase64(authCode)) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("用户授权码必须要做Base64编码！")
                        .addPropertyNode("authCode")
                        .addConstraintViolation();
                return true;
            }
        }
        return false;
    }

    private boolean isBase64(String value) {
        try {
            byte[] decoded = Base64.getDecoder().decode(value);
            String encoded = Base64.getEncoder().encodeToString(decoded);
            return value.equals(encoded);
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

}
